package com.yima.baseproj.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.Data;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class JsonUtils {

    /**
     * 指定接口方法
     */
    public static String admitRemoveJson(String sceneGuid, String[] admitGuids) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("sceneGuid", sceneGuid);
            JSONArray admitArrays = new JSONArray();
            for (String admitGuid : admitGuids) {
                JSONObject admitObject = new JSONObject();
                admitObject.put("admitGuid", admitGuid.replace("\"", ""));
                admitObject.put("type", 1);
                admitArrays.put(admitObject);
            }
            jsonObject.put("admitArrays", admitArrays);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject.toString();
    }

    /**
     * 指定方法使用
     */

    public static String settingUpdateJson(String deviceNo, String source, String deviceConfigs) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode jsonNode = objectMapper.createObjectNode();
        jsonNode.put("source", source);
        jsonNode.put("deviceNo", deviceNo);

        ArrayNode configs = objectMapper.createArrayNode();
        List<ObjectNode> configNodes = objectMapper.readValue(deviceConfigs, objectMapper.getTypeFactory().constructCollectionType(List.class, ObjectNode.class));
        configs.addAll(configNodes);

        jsonNode.set("deviceConfigs", configs);
        return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);
    }

    public static String JsonData(String jsonString) {
        // 查找 "dataList=" 的位置
        int dataListIndex = jsonString.indexOf("dataList=");
        if (dataListIndex == -1) {
            System.out.println("未找到 'dataList='");
            return "未找到";
        }

        // 截取 "dataList=" 之后的部分
        String dataListPart = jsonString.substring(dataListIndex + "dataList=".length());

        // 找到最后一个逗号的位置
        int lastCommaIndex = dataListPart.lastIndexOf(',');
        if (lastCommaIndex == -1) {
            System.out.println("未找到最后一个逗号");
            return "未找到最后一个逗号";
        }

        // 截取最后一个逗号之前的所有内容，即为 dataList 的内容
        String dataListContent = dataListPart.substring(0, lastCommaIndex);

        // 打印截取的 dataList 内容
        System.out.println("截取的 dataList 内容: " + dataListContent);
        return dataListContent;
    }
}


